package pl.edu.agh.admin.core;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import pl.edu.agh.admin.api.CronParameter;
import pl.edu.agh.admin.api.CronTabManager;
import pl.edu.agh.admin.api.PermissionDeniedException;
import pl.edu.agh.admin.api.Task;
import pl.edu.agh.admin.api.User;

public class CronTabManagerMock implements CronTabManager {

	Map<User, List<Task>> user2task;
	
	public CronTabManagerMock(){
		user2task = new HashMap<User, List<Task>>();
		
		List<Task> l1 = new LinkedList<Task>();
		User u1 = new UserImpl("root");
		l1.add(new TaskMock(u1));
		l1.add(new TaskMock(u1));
		l1.add(new TaskMock(u1));
		l1.add(new TaskMock(u1));
		l1.add(new TaskMock(u1));
		user2task.put(u1, l1);
		
		
		List<Task> l2 = new LinkedList<Task>();
		User u2 = new UserImpl("testUser");
		l2.add(new TaskMock(u2));
		l2.add(new TaskMock(u2));
		user2task.put(u2, l2);
		
		
		List<Task> l3 = new LinkedList<Task>();
		User u3 = new UserImpl("wojtek");
		l3.add(new TaskMock(u3));
		l3.add(new TaskMock(u3));
		l3.add(new TaskMock(u3));
		user2task.put(u3, l3);
		
		
		List<Task> l4 = new LinkedList<Task>();
		User u4 = new UserImpl("mateusz");
		l4.add(new TaskMock(u4));
		l4.add(new TaskMock(u4));
		l4.add(new TaskMock(u4));
		l4.add(new TaskMock(u4));
		user2task.put(u4, l4);
		
		
	}
	
	public Collection<User> getUseres() {
		return new LinkedList<User>(user2task.keySet());
	}


	public Collection<Task> getAllTasks() {
		List<Task> ret = new LinkedList<Task>();
		for (List<Task> l : user2task.values()) {
			ret.addAll(l);
		}
		return ret;
	}

	
	public Collection<Task> getUserTasks(User user) {
		return user2task.get(user);
	}

	
	public Task createTask(User user, String cron, String command) {
		Map<CronParameter, String> params = null;
		if(!user2task.containsKey(user)){
			user2task.put(user, new LinkedList<Task>());
		}
		List<Task> list = user2task.get(user);
		if(list.size() == 0){
			params = new HashMap<CronParameter, String>();
			params.put(CronParameter.HOME, "/home");
			params.put(CronParameter.SHELL, "/opt/bash");
		}else{
			params = list.get(0).getParameters();
		}
		TaskMock task = new TaskMock(user, cron, command, params);
		user2task.get(user).add(task);
		return task;
	}

	
	public void deleteTask(Task task) throws PermissionDeniedException {
		for(List<Task> tasks : user2task.values()){
			for(Task t : tasks){
				if(t.equals(task)){
					tasks.remove(task);
					return;
				}
			}
		}
		
	}

	@Override
	public void save() {
	}

	@Override
	public void load() {
		
	}

}
